package czx.wt.web.security;

import czx.wt.mapper.UserMapper;
import czx.wt.util.request.RequestContextUtil;
import czx.wt.util.response.CommResponseEnum;
import czx.wt.util.response.Resp;
import czx.wt.util.response.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description: 自定义用户获取逻辑
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/12/20 0020 10:25
 * @Version: 1.0
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        czx.wt.pojo.User user = userMapper.getUserByUsername(username);
        if (null == user){
            //账号不存在
            try {
                Resp.outResp(RequestContextUtil.getResponse(),ResponseData.failureResponse(CommResponseEnum.USER1));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        logger.info("用户名："+username+" "+"密码："+user.getPassword());
        return new User(user.getUsername(),user.getPassword(),AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
